package com.ming_za.odupdaterserver.core.utils;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 雪花算法
 */
public class SnowflakeIdGenerator {

    private final long startTimestamp; // 设置算法开始时间戳（毫秒）
    private final long workerIdBits = 5L; // 设置机器ID所占的位数
    private final long datacenterIdBits = 5L; // 设置数据中心ID所占的位数
    private final long sequenceBits = 12L; // 设置序列所占的位数

    private final long workerIdShift = sequenceBits; // 机器ID左移位数
    private final long datacenterIdShift = sequenceBits + workerIdBits; // 数据中心ID左移位数
    private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits; // 时间戳左移位数

    private final long sequenceMask = ~(-1L << (int) sequenceBits); // 生成序列的掩码
    private final long workerId; // 机器ID
    private final long datacenterId; // 数据中心ID
    private long sequence = 0L; // 初始序列值
    private long lastTimestamp; // 上一次生成ID的时间戳

    private final AtomicBoolean record = new AtomicBoolean(false);

    /**
     * @param startTimestamp 开始时间戳
     * @param lastTimestamp 最后一次生成时间戳
     * @param workerId 机器id 0~31
     * @param datacenterId 数据中心id 0~31
     * @param callBackFunc id生成后回调方法
     */
    public SnowflakeIdGenerator(long startTimestamp, long lastTimestamp, long workerId, long datacenterId, CallBackFunc callBackFunc) {
        this.startTimestamp = startTimestamp;
        this.lastTimestamp = lastTimestamp;

        this.workerId = workerId;
        this.datacenterId = datacenterId;

        if (workerId > (~(-1L << (int) workerIdBits))) {
            throw new IllegalArgumentException("workerId 不能大于 %d 或小于 0");
        }
        if (datacenterId > (~(-1L << (int) datacenterIdBits))) {
            throw new IllegalArgumentException("datacenterId 不能大于 than %d 或小于 0");
        }

        Thread thread = getThread(callBackFunc);
        thread.start();
    }

    private Thread getThread(CallBackFunc callBackFunc) {
        Thread thread = new Thread(() -> {
            while (true) {
                if (!record.get()) {
                    synchronized (record) {
                        if (!record.get()) {
                            try {
                                record.wait();
                            } catch (InterruptedException e) {
                                break;
                            }
                        }
                    }
                }else {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        break;
                    }
                }

                synchronized (record) {
                    callBackFunc.call(this.lastTimestamp);
                    record.set(false);
                }
            }
        });
        thread.setDaemon(true);
        return thread;
    }

    long lastRecord = 0;

    private void tryRecordLastTimestamp() {
        if (!record.get()) {
            synchronized (record) {
                record.set(true);
            }
        }
        long now = System.currentTimeMillis();
        if (now - lastRecord > 1000) {
            lastRecord = now;
            synchronized (record) {
                record.notify();
            }
        }
    }

    private long offsetTime = 0;

    /**
     * 雪花算法生成ID
     * <pre>如果发生时间回拨，将以上次生成时间作为当前时间继续生成id</pre>
     * @return id；
     */
    public synchronized long nextId() {
        long timestamp = timeGen();

        while (timestamp < lastTimestamp) {
            offsetTime = lastTimestamp - timestamp;
            Msg.getInstance().error("[雪花算法]时间回拨.偏移" + offsetTime + "ms,尝试将时间恢复到上次生成时间,继续生成id");
            timestamp += offsetTime;
        }

        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }

        lastTimestamp = timestamp;

        long id = ((timestamp - startTimestamp) << (int)timestampLeftShift) |
                (datacenterId << (int)datacenterIdShift) |
                (workerId << (int)workerIdShift) |
                sequence;

        tryRecordLastTimestamp();

        return id;
    }

    protected long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    protected long timeGen() {
        return System.currentTimeMillis() + offsetTime;
    }

    /**
     * 生成后回调接口
     */
    public interface CallBackFunc{

        /**
         * 生成后调用该函数
         * @param lastTimestamp 最后一次生成时间
         */
        void call(long lastTimestamp);
    }

}
